package cn.tnar.controller;

import cn.tnar.wx.components.WxMessageComponent;
import cn.tnar.wx.components.WxServerComponent;
import cn.tnar.wx.components.WxUtil;
import cn.tnar.wx.dto.BaseToken;
import cn.tnar.wx.dto.InMsg;
import cn.tnar.wx.dto.OutMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: 陈亮
 * @Date: 2018/10/14 11:49
 */
@Api(tags = "微信-服务器相关以及消息处理")
@RestController
public class WxServerController {

    @Autowired
    private WxUtil wxUtil;

    @Autowired
    private WxMessageComponent wxMessageComponent;

    @Autowired
    private WxServerComponent wxServerComponent;

    @ApiOperation(value = "验证服务器")
    @GetMapping(value = "wechat")
    public String validate(String signature, String timestamp, String nonce, String echostr) {
        if (wxUtil.validate(signature, timestamp, nonce)) {
            return echostr;
        } else {
            return null;
        }
    }

    @ApiOperation(value = "被动回复用户消息")
    @PostMapping(value = "wechat")
    public Object messageHandle(@RequestBody InMsg msg) {
        return wxUtil.beanToXml(wxMessageComponent.passiveReply(msg), OutMsg.class);
    }

    @ApiOperation(value = "获取基础Access_Token")
    @PostMapping(value = "basetoken")
    public BaseToken messageHandle() {
        return wxServerComponent.getBaseToken();
    }

}
